<script setup>
import CloseIcon from '@/components/svgComponents/CloseIcon.vue'

const props = defineProps({
  tags: {
    type: Array,
    default: [],
  },
})

const emit = defineEmits(['change'])

const inputRef = ref(null)

const isFocus = ref(false)

const handleAddTag = () => {
  emit('change', [...props.tags, inputRef.value.value])
  inputRef.value.value = ''
  inputRef.value.blur()
}

const handleDeleteTag = (index) => {
  emit(
    'change',
    props.tags.filter((_, i) => i !== index),
  )
}

const handleAddClick = () => {
  isFocus.value = true
  nextTick(() => {
    inputRef.value.focus()
  })
}

const handleInputBlur = () => {
  isFocus.value = false
}
</script>

<template>
  <div>
    <div class="text-sm text-[--text-3] mb-2">标签</div>
    <div class="flex flex-wrap gap-2">
      <div
        v-for="(tag, index) in tags"
        :key="index"
        class="text-sm text-[--text-b] bg-[--fill-2] p-2 py-1 rounded-full flex gap-[2px] items-center">
        <div class="whitespace-nowrap">{{ tag }}</div>
        <div class="cursor-pointer" @click="handleDeleteTag(index)">
          <CloseIcon color="#000000" width="13" height="13" />
        </div>
      </div>
      <div
        v-if="!isFocus"
        @click="handleAddClick"
        class="text-sm text-[--text-b] bg-[--fill-2] p-2 py-1 rounded-full flex gap-[2px] items-center cursor-pointer">
        <div>+</div>
        <div>添加标签</div>
      </div>
      <div
        v-else
        :class="{ 'border-1 border-[--line-b] box-border': isFocus }"
        class="text-sm text-[--text-b] bg-[--fill-2] p-3 py-1 rounded-full flex gap-[2px] items-center cursor-pointer">
        <input
          type="text"
          class="bg-[--fill-2] w-[60px]"
          ref="inputRef"
          :maxlength="4"
          @blur="handleInputBlur"
          @keydown.enter="handleAddTag" />
      </div>
    </div>
  </div>
</template>
